package utils

import (
	"fmt"
	"pids-cloud-server/config"
	"pids-cloud-server/logging"
	"sync"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
)

var (
	DB *gorm.DB
	mu sync.RWMutex
)

func init() {
	connectDB()
}

// GetDB 获取数据库连接，如果连接无效则重连
func GetDB() *gorm.DB {
	mu.RLock()
	if DB != nil {
		// 检查连接是否有效
		if sqlDB, err := DB.DB(); err == nil {
			if err := sqlDB.Ping(); err == nil {
				mu.RUnlock()
				return DB
			}
		}
	}
	mu.RUnlock()

	// 连接无效，重新连接
	mu.Lock()
	defer mu.Unlock()

	// 双重检查
	if DB != nil {
		if sqlDB, err := DB.DB(); err == nil {
			if err := sqlDB.Ping(); err == nil {
				return DB
			}
		}
	}

	connectDB()
	return DB
}

func connectDB() {
	dbconfig := config.DbConfig
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		dbconfig.Username, dbconfig.Password, dbconfig.Host, dbconfig.Port, dbconfig.Database)

	var err error
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
			TablePrefix:   "m_"},
		Logger:      logger.Default.LogMode(logger.Info),
		PrepareStmt: true,
	})

	if err != nil {
		logging.Error("数据库连接失败", err.Error())
		DB = nil
		return
	}

	// 配置连接池
	sqlDb, err := DB.DB()
	if err != nil {
		logging.Error("获取通用数据库接口失败", err.Error())
		DB = nil
		return
	}

	sqlDb.SetMaxOpenConns(dbconfig.MaxOpenConnections)
	sqlDb.SetMaxIdleConns(dbconfig.MaxIdleConnections)
	sqlDb.SetConnMaxLifetime(time.Hour)
}
